{% extends "base.html" %}

{% block title %}用户管理{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>用户管理</h2>
        {% if current_user.role == 'admin' %}
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
            <i class="fas fa-plus"></i> 添加用户
        </button>
        {% endif %}
    </div>

    {% with messages = get_flashed_messages(with_categories=true) %}
        {% if messages %}
            {% for category, message in messages %}
            <div class="alert alert-{{ category }} alert-dismissible fade show" role="alert">
                {{ message }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="关闭"></button>
            </div>
            {% endfor %}
        {% endif %}
    {% endwith %}

    <div class="card">
        <div class="card-body">
            <table class="table table-striped" id="usersTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>角色</th>
                        {% if current_user.role == 'admin' %}
                        <th>操作</th>
                        {% endif %}
                    </tr>
                </thead>
                <tbody>
                    {% for user in users %}
                    <tr>
                        <td>{{ user.id }}</td>
                        <td>{{ user.username }}</td>
                        <td>{{ user.email }}</td>
                        <td>{{ user.role }}</td>
                        {% if current_user.role == 'admin' %}
                        <td>
                            <button class="btn btn-sm btn-warning edit-user" data-id="{{ user.id }}"
                                    data-username="{{ user.username }}" data-email="{{ user.email }}"
                                    data-role="{{ user.role }}">
                                <i class="fas fa-edit"></i>
                            </button>
                            {% if user.id != current_user.id %}
                            <button class="btn btn-sm btn-danger delete-user" data-id="{{ user.id }}">
                                <i class="fas fa-trash"></i>
                            </button>
                            {% endif %}
                        </td>
                        {% endif %}
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 添加用户模态框 -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addUserModalLabel">添加用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <form id="addUserForm" action="{{ url_for('auth.add_user') }}" method="post">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="username" name="username" required autocomplete="username">
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="email" name="email" required autocomplete="email">
                    </div>
                    <div class="mb-3">
                        <label for="password" class="form-label">密码</label>
                        <input type="password" class="form-control" id="password" name="password" required autocomplete="new-password">
                    </div>
                    <div class="mb-3">
                        <label for="role" class="form-label">角色</label>
                        <select class="form-select" id="role" name="role" required>
                            <option value="researcher">研究员</option>
                            <option value="expert">专家</option>
                            <option value="admin">管理员</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" id="cancelAddBtn">取消</button>
                    <button type="submit" class="btn btn-primary">添加</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑用户模态框 -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editUserModalLabel">编辑用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <form id="editUserForm" method="post">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="edit_username" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="edit_username" name="username" required autocomplete="username">
                    </div>
                    <div class="mb-3">
                        <label for="edit_email" class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="edit_email" name="email" required autocomplete="email">
                    </div>
                    <div class="mb-3">
                        <label for="edit_password" class="form-label">密码 (留空表示不修改)</label>
                        <input type="password" class="form-control" id="edit_password" name="password" autocomplete="new-password">
                    </div>
                    <div class="mb-3">
                        <label for="edit_role" class="form-label">角色</label>
                        <select class="form-select" id="edit_role" name="role" required>
                            <option value="researcher">研究员</option>
                            <option value="expert">专家</option>
                            <option value="admin">管理员</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" id="cancelEditBtn">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteUserModal" tabindex="-1" aria-labelledby="deleteUserModalLabel">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteUserModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
            </div>
            <div class="modal-body">
                确定要删除这个用户吗？此操作不可恢复。
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" id="cancelDeleteBtn">取消</button>
                <form id="deleteUserForm" method="post" style="display: inline;">
                    <button type="submit" class="btn btn-danger">删除</button>
                </form>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block scripts %}
<script>
$(document).ready(function() {
    // 初始化DataTables
    $('#usersTable').DataTable({
        language: {
            url: "{{ url_for('static', filename='js/zh.json') }}"
        }
    });

    // 初始化编辑模态框
    const editModal = new bootstrap.Modal(document.getElementById('editUserModal'), {
        keyboard: true,
        backdrop: true
    });

    // 编辑用户
    $('.edit-user').click(function() {
        const userId = $(this).data('id');
        const username = $(this).data('username');
        const email = $(this).data('email');
        const role = $(this).data('role');

        $('#edit_username').val(username);
        $('#edit_email').val(email);
        $('#edit_role').val(role);
        $('#edit_password').val('');
        $('#editUserForm').attr('action', `/auth/users/${userId}/edit`);
        
        editModal.show();
    });

    // 取消按钮点击事件
    $('#cancelEditBtn').click(function() {
        editModal.hide();
    });

    // 关闭按钮点击事件
    $('.btn-close').click(function() {
        editModal.hide();
    });

    // 模态框隐藏后的事件
    $('#editUserModal').on('hidden.bs.modal', function () {
        $('#editUserForm').trigger('reset');
    });

    // 表单提交前验证
    $('#editUserForm').on('submit', function(e) {
        e.preventDefault();
        
        const username = $('#edit_username').val().trim();
        const email = $('#edit_email').val().trim();
        
        if (!username) {
            alert('用户名不能为空');
            return false;
        }
        
        if (!email) {
            alert('邮箱不能为空');
            return false;
        }
        
        // 验证通过，提交表单
        this.submit();
    });

    // ESC 键关闭模态框
    $(document).keydown(function(e) {
        if (e.key === 'Escape' && $('#editUserModal').hasClass('show')) {
            editModal.hide();
        }
    });

    // 点击模态框外部关闭
    $('#editUserModal').click(function(e) {
        if (e.target === this) {
            editModal.hide();
        }
    });

    // 初始化删除模态框
    const deleteModal = new bootstrap.Modal(document.getElementById('deleteUserModal'), {
        keyboard: true,
        backdrop: true
    });

    // 删除用户按钮点击事件
    $('.delete-user').click(function() {
        const userId = $(this).data('id');
        $('#deleteUserForm').attr('action', `/auth/users/${userId}/delete`);
        deleteModal.show();
    });

    // 取消删除按钮点击事件
    $('#cancelDeleteBtn').click(function() {
        deleteModal.hide();
    });

    // 关闭按钮点击事件（针对删除模态框）
    $('#deleteUserModal .btn-close').click(function() {
        deleteModal.hide();
    });

    // ESC 键关闭删除模态框
    $(document).keydown(function(e) {
        if (e.key === 'Escape' && $('#deleteUserModal').hasClass('show')) {
            deleteModal.hide();
        }
    });

    // 点击删除模态框外部关闭
    $('#deleteUserModal').click(function(e) {
        if (e.target === this) {
            deleteModal.hide();
        }
    });

    // 初始化添加用户模态框
    const addModal = new bootstrap.Modal(document.getElementById('addUserModal'), {
        keyboard: true,
        backdrop: true
    });

    // 添加用户按钮点击事件
    $('.btn-primary[data-bs-toggle="modal"]').click(function() {
        // 重置表单
        $('#addUserForm').trigger('reset');
        addModal.show();
    });

    // 取消添加按钮点击事件
    $('#cancelAddBtn').click(function() {
        addModal.hide();
    });

    // 添加用户表单提交前验证
    $('#addUserForm').on('submit', function(e) {
        e.preventDefault();
        
        const username = $('#username').val().trim();
        const email = $('#email').val().trim();
        const password = $('#password').val();
        
        if (!username) {
            alert('用户名不能为空');
            return false;
        }
        
        if (!email) {
            alert('邮箱不能为空');
            return false;
        }
        
        if (!password) {
            alert('密码不能为空');
            return false;
        }

        // 验证邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            alert('请输入有效的邮箱地址');
            return false;
        }
        
        // 验证通过，提交表单
        this.submit();
    });

    // 添加用户模态框隐藏后的事件
    $('#addUserModal').on('hidden.bs.modal', function () {
        $('#addUserForm').trigger('reset');
    });

    // ESC 键关闭添加模态框
    $(document).keydown(function(e) {
        if (e.key === 'Escape' && $('#addUserModal').hasClass('show')) {
            addModal.hide();
        }
    });

    // 点击添加模态框外部关闭
    $('#addUserModal').click(function(e) {
        if (e.target === this) {
            addModal.hide();
        }
    });

    // 初始化所有警告框的关闭按钮
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        new bootstrap.Alert(alert);
    });

    // 3秒后自动隐藏消息
    setTimeout(function() {
        $('.alert').alert('close');
    }, 3000);
});
</script>
{% endblock %} 